import type { NextApiRequest, NextApiResponse } from 'next'
import { query } from '@/lib/db'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { id } = req.query

  if (req.method === 'GET') {
    try {
      const result = await query({
        query: 'SELECT * FROM users WHERE id = ?',
        values: [id],
      })
      const user = result[0]
      if (user) {
        res.json(user)
      } else {
        res.status(404).json({ error: '用户不存在' })
      }
    } catch (error) {
      res.status(500).json({ error: '查询失败' })
    }
  } else if (req.method === 'PUT') {
    try {
      await query({
        query: 'UPDATE users SET name = ? WHERE id = ?',
        values: [req.body.name, id],
      })
      res.json({ success: true })
    } catch (error) {
      res.status(500).json({ error: '更新失败' })
    }
  }
}